/*
 * @(#)JsonView.java $version 2011. 9. 28.
 *
 * Copyright 2007 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package com.luffy.view;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.view.AbstractView;

import com.luffy.message.model.ErrorMessage;
import com.luffy.message.model.ResultMessage;
import com.luffy.message.model.SuccessMessage;
import com.thoughtworks.xstream.XStream;

/**
 * @author Administrator
 */
public class xmlView extends AbstractView{
	public static final String DEFAULT_CONTENT_TYPE = "application/xml";
	
	private XStream xmlXstream;
	
	public xmlView() {
		setContentType(DEFAULT_CONTENT_TYPE);
		xmlXstream = new XStream();
		xmlXstream.processAnnotations(SuccessMessage.class);
		xmlXstream.processAnnotations(ResultMessage.class);
		xmlXstream.processAnnotations(ErrorMessage.class);
	}

	/**
	 * @param model
	 * @param request
	 * @param response
	 * @throws Exception
	 * @see org.springframework.web.servlet.view.AbstractView#renderMergedOutputModel(java.util.Map, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void renderMergedOutputModel(Map<String, Object> model,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		System.out.println(xmlXstream.toXML(model));
		writeToResponse(response, xmlXstream.toXML(model));		
		
	}
	
	/**
	 *  
	 * @param response response
	 * @param content content
	 * @throws IOException
	 */
	private void writeToResponse(HttpServletResponse response, String content) throws IOException {
		OutputStream os = response.getOutputStream();
		byte [] bytes = content.getBytes("UTF-8");
		os.write(bytes);
		os.flush();
		os.close();
		response.setContentLength(bytes.length);
	}
}
